package com.zjb.wxlisener.interceptor;

import com.alibaba.fastjson.JSONObject;
import com.zjb.wxlisener.JavaBean.Result;
import com.zjb.wxlisener.until.JWTUntil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

@Slf4j
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse res, Object handler) throws Exception {
        String url = req.getRequestURL().toString();
        log.info("url={}",url);
        if (url.contains("login")){
            log.info("请求登录");
            return true;
        }
        String token = req.getHeader("mytoken");
        if (!StringUtils.hasLength(token)){
            log.info("没有令牌");
            Result error = Result.error("NOT_LOGIN");
            String json = JSONObject.toJSONString(error);
            res.getWriter().write(json);
            return false;
        }
        try {
            JWTUntil.konwJWT(token);
        }catch (Exception e){
            log.info("解析失败");
            Result result = Result.error("NOT_LOGIN");
            String json1 = JSONObject.toJSONString(result);
            res.getWriter().write(json1);
            return false;
        }
        return true;
    }

}
